import { ApiResponse, ArticleDetail, CommentRes, Comment } from '@/types/data'
import { RootThunkAction, ArticleAction } from '@/types/store'
import request from '@/utils/request'

// 获取文章详情
export const getArticleInfo = (id: string): RootThunkAction => {
  return async (dispatch) => {
    const res = await request.get<ApiResponse<ArticleDetail>>(`/articles/${id}`)
    dispatch({
      type: 'article/setArticleInfo',
      payload: res.data.data
    })
  }
}

// 获取文章的评论
export const getCommentList = (id: string, offset?: string): RootThunkAction => {
  return async (dispatch) => {
    const res = await request.get<ApiResponse<CommentRes>>('/comments', {
      params: {
        type: 'a', // 评论类型，a-对文章(article)的评论，c-对评论(comment)的回复
        source: id,
        offset
      },
    })
    dispatch({
      type: 'article/saveComment',
      payload: res.data.data
    })
  }
}

// 点赞/取消点赞
export const likeAritcle = (id: string, attitude: number): RootThunkAction => {
  return async (dispatch) => {
    if (attitude === 1) {
      // 取消点赞
      await request.delete('article/likings/' + id)
    } else {
      // 点赞
      await request.post('article/likings', { target: id })
    }
    // 更新
    await dispatch(getArticleInfo(id))
  }
}

// 收藏/取消收藏
export const collectArticle = (id: string, is_collected: boolean): RootThunkAction => {
  return async (dispatch) => {
    if (is_collected) {
      // 取消收藏
      await request.delete('article/collections/' + id)
    } else {
      // 收藏
      await request.post('article/collections', { target: id })
    }
    // 更新
    await dispatch(getArticleInfo(id))
  }
}

// 关注用户/取消关注
export const followUser = (userId: string, is_follow: boolean): RootThunkAction => {
  return async (dispatch, getState) => {
    if (is_follow) {
      // 取消关注
      await request.delete('user/followings/' + userId)
    } else {
      // 关注
      await request.post('user/followings', { target: userId })
    }
    await dispatch(getArticleInfo(getState().article.info.art_id))
  }
}

// 发表评论
export const addComment = (
  articleId: string,
  content: string
): RootThunkAction => {
  return async (dispatch) => {
    const res = await request.post<ApiResponse<{ new_obj: Comment }>>(
      '/comments',
      {
        target: articleId,
        content,
      }
    )
    dispatch({
      type: 'article/saveNewComment',
      payload: res.data.data.new_obj,
    })
  }
}

// 增加回复数量
export function addReplyCount(commentId: string): ArticleAction {
  return {
    type: 'article/addReplyCount',
    payload: commentId
  }
}